package com.tanjun.web.annotation.aspect;

import cn.hutool.core.util.StrUtil;
import com.tanjun.common.enums.err.LoginErrCode;
import com.tanjun.common.exception.BizException;
import com.tanjun.web.annotation.HasPermission;
import com.tanjun.web.service.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

@Component
@Aspect
@Slf4j
public class HasPermissionAspect {
    /**
     * 登录验证
     *
     * @param joinPoint
     * @return
     */
    @Around("@within(com.tanjun.web.annotation.HasPermission)||@annotation(com.tanjun.web.annotation.HasPermission)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 1. 检查方法上是否有注解
        HasPermission methodHasPermission = method.getAnnotation(HasPermission.class);
        if (methodHasPermission != null) {
            log.info("method has HasPermission, method name:{},hasPermission:{}", method.getName(), methodHasPermission);
            checkHasPermission(methodHasPermission);
        }

        HasPermission classHasPermission = joinPoint.getTarget().getClass().getAnnotation(HasPermission.class);
        if (classHasPermission != null) { // 避免重复处理
            log.info("class has HasPermission,class name: {}", signature.getClass().getName());
            checkHasPermission(classHasPermission);
        }
        // 执行目标方法
        return joinPoint.proceed();

    }

    private void checkHasPermission(HasPermission hasPermission) {
        List<String> permissions = LoginUserUtil.getUserPermission();
        if (StrUtil.isNotEmpty(hasPermission.value())&& !permissions.contains(hasPermission.value())) {
            throw new BizException(LoginErrCode.NOT_PERMISSION);
        }

    }
}
